//
//  AppDelegate.swift
//  jiahui
//
//  Created by 3tee on 2024/11/21.
//

import UIKit
import IQKeyboardManagerSwift
import RxSwift
import Moya
import avd_sdk

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
     
    typealias StringBlock = (String,String) -> Void
    
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        DispatchQueue.global(qos: .default).async {
            self.reqToken { access, secret in
                ThreeTManager.shardInstance.initEng(WithUrl: Constant.mediaSever)
            }
        }
        // Override point for customization after application launch.
        IQKeyboardManager.shared.enable = true
        window = UIWindow(frame: UIScreen.main.bounds)
        let rootVC: UINavigationController = UINavigationController(rootViewController: JoinViewController())
        let tabbarVC: UITabBarController = MainTabBarController()
        if  UserDefaults.standard.bool(forKey: Constant.key_isLogin) {
            window?.rootViewController =  UINavigationController(rootViewController: tabbarVC)
        }else{
            window?.rootViewController = rootVC
        }
        window?.makeKeyAndVisible()
        DBManager.shared.createTab()
      
        return true
    }



}

extension AppDelegate{
    func reqToken(_ complete: @escaping StringBlock){
        let parms = ["access_key":"demo_access","secret_key":"demo_secret","timestamp":Int(Date().timeIntervalSince1970)] as [String : Any]
        do {
             let jsonData = try JSONSerialization.data(withJSONObject: parms, options: [])
             let json = String(data: jsonData, encoding:String.Encoding.utf8)
            if let rsaJson = RSA.encryptString(json, publicKey: RSA_Public_key){
                let provider = MoyaProvider<RestAPI>(plugins:[NetworkLoggerPlugin()])
                provider.request(.getToken(rsaJson)) { result in
                    switch result {
                    case .success(let response):
                        let statusCode = response.statusCode
                        let data = response.data
                        let jsonDic = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
                        if let tokenData = jsonDic?["data"] as? String{
                            let rsaToken = RSA.decryptString(tokenData, privateKey: RSA_Private_key)
                            if let rsaData: Data = rsaToken?.data(using: .utf8){
                                let rsaDic = try? JSONSerialization.jsonObject(with: rsaData) as? [String: Any]
                                print("解密之后的token dic = \(String(describing: rsaDic))")
                                
                                if let access = rsaDic?["access_key"] as? String,let secret = rsaDic?["secret_key"] as? String {
                                    UserDefaultsPlugin.setValue(access, key: Constant.key_access)
                                    UserDefaultsPlugin.setValue(secret, key: Constant.key_secret)
                                    complete(access,secret)
                                }
                               
                            }
                            
                        }
                        
                        print("获取token成功 code = \(statusCode) json = \(json)")
                    case .failure(let error):
                        print("获取token失败")
                        
                    }
                }
                
            }
        } catch  {
            print("error = \(error)")
        }
        
        
    }
}
